package dca.sistemascontrole.view.configuracao;

import dca.sistemascontrole.handler.HandlerMainFrame;
import dca.sistemascontrole.handler.HandlerPainelMalhaVisível;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import static java.lang.Math.sqrt;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.commons.math3.complex.Complex;

/**
 *
 * @author Rafael
 */
public class PanelVariaveisEstado extends javax.swing.JPanel {

    private HandlerMainFrame handlerMainFrame;

    public PanelVariaveisEstado(HandlerMainFrame handlerMainFrame) {
        initComponents();

        this.handlerMainFrame = handlerMainFrame;

        adicionarDocumentListener();

        addHierarchyListener(new HierarchyListener() {
            public void hierarchyChanged(HierarchyEvent e) {
                hierarchyChangedEvent();
            }
        });
    }

    private void hierarchyChangedEvent() {
        //TODO Por enquanto manter comentado
//        boolean isExibidoAtual = isShowing();
//        if (HandlerPainelMalhaVisível.getMalhaAtual() != HandlerPainelMalhaVisível.VARIAVEIS_ESTADO && isExibidoAtual) {
//            handlerMainFrame.interromper();
//
//            HandlerPainelMalhaVisível.setMalhaAtual(HandlerPainelMalhaVisível.VARIAVEIS_ESTADO);
//        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtReal1 = new javax.swing.JTextField();
        txtImangario1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtGanho1 = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtReal2 = new javax.swing.JTextField();
        txtImangario2 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtGanho2 = new javax.swing.JTextField();
        btnDefinir = new dca.sistemascontrole.view.components.CustomButton();

        setBackground(new java.awt.Color(255, 255, 255));

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Polo 1"));

        jLabel1.setText("Real:");

        jLabel2.setText("Imaginária:");

        jLabel3.setText("Ganho:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtImangario1)
                            .addComponent(txtGanho1)
                            .addComponent(txtReal1, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtReal1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtImangario1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtGanho1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2, jLabel3, txtImangario1, txtReal1});

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Polo 2"));

        jLabel4.setText("Real:");

        jLabel5.setText("Imaginária:");

        jLabel6.setText("Ganho:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtImangario2)
                    .addComponent(txtGanho2)
                    .addComponent(txtReal2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtReal2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtImangario2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtGanho2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnDefinir.setBackground(new java.awt.Color(250, 250, 250));
        btnDefinir.setText("Definir");
        btnDefinir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDefinirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnDefinir, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnDefinir, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnDefinirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDefinirActionPerformed
        float ganho1;
        float ganho2;

        String ganho1STR = txtGanho1.getText().trim().replace(",", ".");
        if (!validarEntrada(ganho1STR)) {
            JOptionPane.showMessageDialog(this, "Ganho 1 inválido");
            return;
        }
        ganho1 = Float.parseFloat(ganho1STR);

        String ganho2STR = txtGanho2.getText().trim().replace(",", ".");
        if (!validarEntrada(ganho2STR)) {
            JOptionPane.showMessageDialog(this, "Ganho 2 inválido");
            return;
        }
        ganho2 = Float.parseFloat(ganho2STR);

        handlerMainFrame.setObservador(ganho1, ganho2);
    }//GEN-LAST:event_btnDefinirActionPerformed

    private boolean validarEntrada(String s) {
        try {
            Float.parseFloat(s);
        } catch (NumberFormatException ex) {
            return false;
        }

        return true;
    }

    private void calcularGanhos() {
        if (txtGanho1.hasFocus() || txtGanho2.hasFocus()) {
            return;
        }

        float real1;
        float real2;
        float imaginario1;
        float imaginario2;

        String real1STR = txtReal1.getText().trim().replace(",", ".");
        if (!validarEntrada(real1STR)) {
            return;
        }
        String real2STR = txtReal2.getText().trim().replace(",", ".");
        if (!validarEntrada(real2STR)) {
            return;
        }
        String imaginario1STR = txtImangario1.getText().trim().replace(",", ".");
        if (!validarEntrada(imaginario1STR)) {
            return;
        }
        String imaginario2STR = txtImangario2.getText().trim().replace(",", ".");
        if (!validarEntrada(imaginario2STR)) {
            return;
        }

        real1 = Float.parseFloat(real1STR);
        real2 = Float.parseFloat(real2STR);
        imaginario1 = Float.parseFloat(imaginario1STR);
        imaginario2 = Float.parseFloat(imaginario2STR);
        Complex polo1 = new Complex(real1, imaginario1);
        Complex polo2 = new Complex(real2, imaginario2);
        Complex alpha1 = polo1.add(polo2);
        alpha1 = alpha1.multiply(-1);
        Complex alpha2 = polo1.multiply(polo2);

        double G[][] = new double[2][2];
        G[0][0] = 0.9934570;
        G[0][1] = 0;
        G[1][0] = 0.0065215;
        G[1][1] = 0.9934570;
        double G2[][] = new double[2][2];
        for (int row = 0; row < G.length; row++) // multiplicação das matrizes
        {
            for (int column = 0; column < G[row].length; column++) {
                double aux = 0;

                for (int i = 0; i < G[row].length; i++) {

                    try {

                        aux = aux + G[row][i] * G[i][column];

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }

                G2[row][column] = aux;

            }
        }
        Complex alpha1xG[][] = new Complex[2][2];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                alpha1xG[i][j] = alpha1.multiply(G[i][j]);
            }
        }
        Complex alpha2xI[][] = new Complex[2][2];
        alpha2xI[0][0] = alpha2;
        alpha2xI[1][0] = alpha2.multiply(0);
        alpha2xI[0][1] = alpha2.multiply(0);
        alpha2xI[1][1] = alpha2;
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                alpha1xG[i][j] = alpha1xG[i][j].add(alpha2xI[i][j]);
                alpha1xG[i][j] = alpha1xG[i][j].add(G2[i][j]);
                System.out.print(alpha1xG[i][j].toString() + " ");
            }
            System.out.print("\n");
        }

        double M[] = new double[2];
        M[0] = 154.33825;
        M[1] = 0;
        Complex L1;
        Complex L2;
        L1 = alpha1xG[0][0].multiply(M[0]);
        L2 = alpha1xG[1][0].multiply(M[0]);

        this.txtGanho1.setText("" + L1.getReal());
        this.txtGanho2.setText("" + L2.getReal());
    }

    private void calcularPolos() {
        if (!txtGanho1.hasFocus() && !txtGanho2.hasFocus()) {
            return;
        }

        double ganho1;
        double ganho2;

        String ganho1STR = txtGanho1.getText().trim().replace(",", ".");
        if (!validarEntrada(ganho1STR)) {
            return;
        }

        String ganho2STR = txtGanho2.getText().trim().replace(",", ".");
        if (!validarEntrada(ganho2STR)) {
            return;
        }

        ganho1 = Double.parseDouble(ganho1STR);
        ganho2 = Double.parseDouble(ganho2STR);
        double L1 = ganho1;
        double L2 = ganho2;
        double M[] = new double[2];
        M[0] = 154.33825;
        M[1] = 0;
        double L[] = new double[2];
        L[0] = L1;
        L[1] = L2;
        double G[][] = new double[2][2];
        G[0][0] = 0.9934570;
        G[0][1] = 0;
        G[1][0] = 0.0065215;
        G[1][1] = 0.9934570;
        double G2[][] = new double[2][2];
        for (int row = 0; row < G.length; row++) // multiplicação das matrizes
        {

            for (int column = 0; column < G[row].length; column++) {

                double aux = 0;

                for (int i = 0; i < G[row].length; i++) {

                    try {

                        aux = aux + G[row][i] * G[i][column];

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }

                G2[row][column] = aux;

            }
        }
        double G2xM[] = new double[2];
        for (int column = 0; column < 2; column++) {

            double aux = 0;

            for (int i = 0; i < 2; i++) {
                aux = aux + G2[column][i] * M[i];
            }

            G2xM[column] = aux;

        }

        double L_G2xM[] = new double[2];
        L_G2xM[0] = L[0] - G2xM[0];
        L_G2xM[1] = L[1] - G2xM[1];
        double GM[] = new double[2];
        for (int column = 0; column < 2; column++) {

            double aux = 0;

            for (int i = 0; i < 2; i++) {
                aux = aux + G[column][i] * M[i];
            }

            GM[column] = aux;

        }
        double alfa1 = L_G2xM[1] / GM[1];
        double alfa2 = (L_G2xM[0] - GM[0] * alfa1) / M[0];
        Complex P2;
        Complex P1;
        if (((alfa1 * alfa1) - (4 * alfa2)) < 0) {
            P2 = new Complex(-alfa1 / 2, sqrt((4 * alfa2) - alfa1 * alfa1) / 2);
            P1 = P2.add(alfa1).multiply(-1);
        } else {
            P2 = new Complex((-alfa1 / 2) + sqrt((alfa1 * alfa1) - (4 * alfa2)) / 2, 0);
            P1 = P2.add(alfa1).multiply(-1);
        }
        this.txtReal1.setText("" + P1.getReal());
        this.txtImangario1.setText("" + P1.getImaginary());
        this.txtReal2.setText("" + P2.getReal());
        this.txtImangario2.setText("" + P2.getImaginary());
    }

    private void adicionarDocumentListener() {
        txtGanho1.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                calcularPolos();
            }

            public void removeUpdate(DocumentEvent e) {
                calcularPolos();
            }

            public void changedUpdate(DocumentEvent e) {
                calcularPolos();
            }
        });
        txtGanho2.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                calcularPolos();
            }

            public void removeUpdate(DocumentEvent e) {
                calcularPolos();
            }

            public void changedUpdate(DocumentEvent e) {
                calcularPolos();
            }
        });

        txtReal1.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void removeUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void changedUpdate(DocumentEvent e) {
                calcularGanhos();
            }
        });
        txtReal2.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void removeUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void changedUpdate(DocumentEvent e) {
                calcularGanhos();
            }
        });

        txtImangario1.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void removeUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void changedUpdate(DocumentEvent e) {
                calcularGanhos();
            }
        });
        txtImangario2.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void removeUpdate(DocumentEvent e) {
                calcularGanhos();
            }

            public void changedUpdate(DocumentEvent e) {
                calcularGanhos();
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dca.sistemascontrole.view.components.CustomButton btnDefinir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField txtGanho1;
    private javax.swing.JTextField txtGanho2;
    private javax.swing.JTextField txtImangario1;
    private javax.swing.JTextField txtImangario2;
    private javax.swing.JTextField txtReal1;
    private javax.swing.JTextField txtReal2;
    // End of variables declaration//GEN-END:variables
}
